<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\config;
use fast\Tool;
use think\Cache;
use app\common\model\VisitorMessage;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 聊天客服
     * @return mixed
     */
    public function kfwindow()
    {
        $token = $this->request->param('token', 0);
        $kfColor = $this->request->param('color', "#1f78f0");
        $kfStringtxt = $this->request->param('stringtxt', "微信速聊，微信沟通");
        $kfStringtxt = urldecode($kfStringtxt);

        if(empty($token)){
            echo "请选择客服！";exit;
        }
        $config = Config::get('chat');
        $this->assign('config', $config);
        $this->assign('user_agent', request()->server('HTTP_USER_AGENT'));
        $this->assign('join_ip', request()->ip());
        $this->assign('domain', Tool::getDomain());
        $this->assign('kf_color',$kfColor);
        $this->assign("kf_string_txt",$kfStringtxt);
        return $this->fetch('', ['uuid' => Tool::get_uuid(), 'isHttps' => Tool::is_https(),'token'=>$token]);
    }

    public function getRecord($token,$uuid,$page){
        if(empty($token)){
            echo "token不能为空！";exit;
        }
        if(empty($uuid)){
            echo "uuid不能为空！";exit;
        }
        if(empty($page)){
            $page = 1;
        }
//        $params = $this->request->param();
        $limit = 10;
        list($userId,$companyId) = Tool::de_token($token);
        $where = ['user_id'=>$userId,'uuid'=>$uuid,'company_id'=>$companyId];
        $message_list = model('ChatMessage')->where($where)->order('add_time desc')->paginate($limit, false, ['page' => $page]);
//        echo model('ChatMessage')->getLastSql();exit;
        if(!empty($message_list)){
            foreach($message_list as $key=>$val){
                if (date('m-d', strtotime('-1 day')) == date('m-d', $val['add_time'])) {
                    $message_list[$key]['time'] = '昨天 ' . date('H:i', $val['add_time']);
                } elseif (date('m-d') == date('m-d', $val['add_time'])) {
                    $message_list[$key]['time'] = date('H:i', $val['add_time']);
                } else {
                    $message_list[$key]['time'] = date('m-d', $val['add_time']) . ' ' . date('H:i', $val['add_time']);
                }
            }
        }
        $this->result($message_list, 1, '', 'json');

    }

    public function submitMessage(){
        $errorConter = "";
        //接受数字
        $tel = $this->request->param('xpz_message_tel_if');
        $token = $this->request->param('xpz_message_token_if');
        $name = $this->request->param('xpz_message_name_if');
        $content =  $this->request->param('xpz_message_content_if');

        $errorConter .= 'tel:'.$tel."===token:".$token."===name:".$name."===content:".$content;

        $ip = request()->ip();
        if(!$this->getLiuyanCache($ip)){
            $error = $ip."此ip今天留言已超过限制！";
            $this->wirteErrorLog($errorConter."===error:".$error);
            exit;
        }

        //验证规则
        if(strlen($content) < 6){
            $error = "留言内容不能少于6个字！";
            $this->wirteErrorLog($errorConter."===error:".$error);
            exit;
        }

        if(strlen($name) == 0){
            $error = "姓名不能为空！";
            $this->wirteErrorLog($errorConter."===error:".$error);
            exit;
        }

        if(!preg_match('/^1\d{10}$/',$tel)){
            $error = "手机号不正确！";
            $this->wirteErrorLog($errorConter."===error:".$error);
            exit;
        }

        if(empty($token)){
            $error = "token不能为空！";
            $this->wirteErrorLog($errorConter."===error:".$error);
            exit;
        }
        $tokenArr = Tool::de_token($token);
        if(empty($tokenArr)){
            $error = "token解码错误！";
            $this->wirteErrorLog($errorConter."===error:".$error);
            exit;
        }

        $kfRs = model("User")->where(['id'=>$tokenArr[0]])->find();
        if(empty($kfRs['id'])){
            $error = "客服不存在！";
            $this->wirteErrorLog($errorConter."===error:".$error);
            exit;
        }


        $userAgent = request()->server('HTTP_USER_AGENT');
        $time = time();
        $browserArr = Tool::getBrowser($userAgent);
        $browser = "";
        if(isset($browserArr['browser'])){
            $browser = $browserArr['browser'];
        }
        $version = "";
        if(isset($browserArr['version'])){
            $version = $browserArr['version'];
        }

        $data = [
            'name' => $name,
            'tel' => $tel,
            'content' => $content,
            'ip' => $ip,
            'add_time' => $time,
            'admin_id' => $tokenArr[0],
            'browser' => $browser.'_'.$version,
        ];
        $rs = VisitorMessage::create($data);
        if(isset($rs['id']) && !empty($rs['id'])){
            //设置缓存
            $this->setLiuyanCache($ip);
            //发送微信通知
            $loginToken = Tool::enLoginToken($kfRs['id'], $kfRs['openid']);
            Tool::messageNotice($kfRs['openid'], $rs['id'], $name, $content, $loginToken);
            echo "留言提交成功！";
        } else {
            $error = "留言入库失败！";
            $this->wirteErrorLog($errorConter."===error:".$error);
            exit;
        }
    }

    /**
     * 判断是否提交可以提交
     * @param string $ip
     * @return boolean
     */
    private function getLiuyanCache($ip){
        $ip = 'cache_liuyan_'.$ip;
        $count = Cache::get($ip);
        if($count > Config::get('xpz.liuyan_submit_count')){
            return false;
        }
        return true;
    }
    /**
     * 设置提交次数缓存
     * @param string $ip
     */
    private function setLiuyanCache($ip){
        $ip = 'cache_liuyan_'.$ip;
        $count = Cache::get($ip);
        if(!empty($count)){
            Cache::inc($ip, 1);
        } else {
            Cache::set($ip, 1, Config::get('xpz.liuyan_submit_count_time'));
        }
    }

    private function wirteErrorLog($content){
        Tool::mylog(true, "网站留言错误：", $content,"liuyan_error");
    }





    public function test(){
//        echo md5("572VAFIJWYEm");exit;
//        print_r($this->ttt(9));
//        exit;
        return $this->fetch();
    }

    private function ttt($n){
        $arr = [2,3,5,6,7,9,11,32,56,66,77,88,99];
        echo $this->dg($arr,5,count($arr)-1);
        exit;
        $arr[0] = 1;
        $arr[1] = 1;
        for($i=2;$i<$n;$i++){
            $arr[$i] = $arr[$i-2] + $arr[$i-1];
        }
        return $arr;
    }

    private function dg($array,$search,$len){

        $mid = (int)($len/2);
        if($array[$mid] == $search){
            return $mid;
        } else if($array[$mid] > $search){
            return $this->dg($array,$search,$len-1);
        } else {
            return $this->dg($array,$search,$len+1);
        }
    }

    private function xx($array,$search,$lenth){
        $mid = (int)($lenth/2);
        if($array[$mid] == $search){
            return $mid;
        } else if($array[$mid] > $search){
            return xx($array,$search,$lenth-1);
        } else {
            return xx($array,$search,$lenth+1);
        }
    }


}
